package com.gsa.core.interceptor;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gsa.core.exchange.Exchange;
import com.gsa.core.http.Request;
import com.gsa.core.rules.ProxyRule;
import com.gsa.core.transport.http.HttpTransport;
import com.gsa.core.ws.relocator.Relocator;
import org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor;
import org.springframework.ws.soap.security.callback.AbstractCallbackHandler;
import org.springframework.ws.soap.security.wss4j.callback.SimplePasswordValidationCallbackHandler;

public class SOAPEncrytorInterceptor extends AbstractInterceptor {

	private static Log log = LogFactory.getLog(SOAPEncrytorInterceptor.class.getName());
	
	private String host;
	XwsSecurityInterceptor xsi;
	SimplePasswordValidationCallbackHandler spvch;
	AbstractCallbackHandler ach;

	public Outcome handleResponse(Exchange exchange) throws Exception {
		log.debug("handleRequest");
		if ( exchange.getRule() instanceof ProxyRule ) return  Outcome.CONTINUE;
		
		if (!Request.METHOD_GET.equals(exchange.getRequest().getMethod())) 
			return Outcome.CONTINUE;
		
		if (exchange.getResponse().getHeader().getContentType() == null) 
			return Outcome.CONTINUE;
		
		
		if (!exchange.getResponse().isXML())
			return Outcome.CONTINUE;
		
		log.debug("Changing endpoint address in WSDL");
		//	xsi.

	
		//spvch.handle(arg0);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		new Relocator(stream, getSourceHost(exchange), exchange.getRule().getKey().getPort() ).relocate(new ByteArrayInputStream(exchange.getResponse().getBody().getContent()));
		exchange.getResponse().setBodyContent(stream.toByteArray());
		return Outcome.CONTINUE; 
	}
	

	private String getSourceHost(Exchange exchange) {
		if (host != null)
			return host;
		log.debug("Host header: "+exchange.getRequest().getHeader().getHost());
	    String sourcehost = ((String)exchange.getProperty(HttpTransport.HEADER_HOST)).replaceFirst(":.*", "");
	    log.debug("host " + sourcehost );
		if (sourcehost == null) {
			return "localhost"; //change for  testing  - 11/04/2010
		}
		return sourcehost;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	
	

}
